<?php
namespace app\admin\controller;

use app\admin\model\Device as DeviceModel;
use app\admin\model\DeviceGroup as DeviceGroupModel;
use app\admin\model\Agent as AgentModel;
use app\admin\model\Account as AccountModel;
use app\admin\model\Sn as SnModel;
use app\admin\model\DeviceModel as DeviceModelModel;
use think\Db;
use think\Request;


class Device extends Base
{
    public function index()
    {
        $model = new DeviceModel;
        $dGroupModel = new DeviceGroupModel;
        $agentModel = new AgentModel;
        $accountModel = new AccountModel;
        $mModel = new DeviceModel;
        $sModel = new SnModel;

        $phname = $this->request->param("phname");

        //渲染页面模板
        $m = $model->field('d.id,d.sn_id,d.sim,d.imei,d.name,d.created_at as actived_at,d.worktime,d.state,u.username,f.name as fname,g.name as gname,d.created_at,m.name as mname,s.sn,s.imei')
            ->alias('d')
            ->join('user u','d.user_id = u.id ','left')
            ->join('sn s','d.sn_id = s.id ','left')
            ->join('franchiser f','d.franchiser_id = f.id','left')
            ->join('device_group g','d.device_group_id = g.id','left')
            ->join('device_model m','d.device_model_id = m.id','left')
            ->order('d.id','desc');
        //->select();
        //->paginate(5);

        if(!empty($phname)){
            $model->where('s.sn|s.imei|u.username','like', '%'.$phname.'%');
        }
        $result = $model->paginate(10,false,[
            'query'=>['phname'=>$phname]
        ]);

        //渲染用户组
        $dGroup = $dGroupModel->field('id,name')->select();
        //渲染代理商
        $agent = $agentModel->field('id,name')->select();
        $account = $accountModel->field('id,username')->select();
        $dm = $mModel->field('id,name')->select();
        $sn = $sModel->field('id,sn,imei')->select();

        //计算总共记录条数
        $count = $result->total();
        //分页
        $page = $result->render();

        //接收ajax传递的值
        $request = request();
        $ispost = $request->isPost();
        if($ispost){
            $id = $_POST["viewId"];
            $view = $model->field('d.id,d.sn_id,d.sim,d.user_id,d.imei,d.name,d.created_at,d.worktime,d.device_group_id,d.device_model_id,d.franchiser_id,c.car_brand,c.car_model,p.longitude,p.latitude,p.radius')
                    ->alias('d')
                    ->join('car c','d.id = c.device_id ','left')
                    ->join('pen p','d.id = p.device_id ','left')
                    ->where("d.id",$id)
                    ->find();
            // $view['state'] = 1;
            // redis 中取值查看
            $redis = \jm\helper\Db::getRedisIns();
            $deviceRedisInfo = $redis->hget('devices', $view['imei']);
            if ($deviceRedisInfo === false) {
                $view['state'] = 0;
            } else {
                $deviceDecodeInfo = json_decode($deviceRedisInfo, true);
                $view['state'] = \jm\helper\Db::isOnline($deviceDecodeInfo);
            }
            return json([
                'code' => 200,
                'view' => $view,
            ]);
        }

        $this->assign('currentPage', $result->currentPage());
        $this->assign('lastPage', $result->lastPage());
        $this->assign('page', $page);
        $this->assign('dGroup', $dGroup);
        $this->assign('dm', $dm);
        $this->assign('sn', $sn);
        $this->assign('agent', $agent);
        $this->assign('account', $account);
        $this->assign('device', $result);
        $this->assign('count', $count);
        $this->assign('empty', "暂无数据");
        return $this->fetch();
    }

    //新增数据
    public function create(){
        $model = new DeviceModel;
        //接收ajax传递的值
        $ispost = $this->request->isPost();
        if($ispost){
            $formdata = $this->request->post();
            $username = Db::query("select id from ". $this->dbTablePrefix ."device where `name`='".$formdata['name']."' and deleted_at is NULL ");

            if(!empty($username)){
                return json([
                    'code' => 4000,
                    'message'=>"用户名已存在"
                ]);
            }
            $result = $model->allowField(true)->save($formdata);

            if($result == 1){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //修改数据处理
    public function edit($id)
    {
        $model = new DeviceModel;
        //接收ajax传递的值
        $ispost = $this->request->isPost();

        if($ispost){
            $formdata = $this->request->post();

            $result = $model->allowField(true)->save($formdata,['id'=>$id]);

            if($result == 1){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //删除单条记录
    public function delete($id)
    {
        $result = DeviceModel::update(['deleted_at'=>date('Y-m-d H:i:s')],['id'=>$id]);//软删除

        if($result){
            return json([
                'code' => 200,
            ]);
        }

    }

    //批量删除
    public function deleteArr()
    {
        $ispost = $this->request->isPost();
        if ($ispost) {
            $idArr = $this->request->post();

            $result = DeviceModel::where('id','exp','in('.implode(',',$idArr['id']).')')->update(['deleted_at'=>date('Y-m-d H:i:s')]);//软删除

            if($result){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }
}